/****************************************************************************************
 * 
 *  Author:         CFY
 *  Date:           2025-07-10
 *  Description:    数据上报 处理数据的模块
 *  Version:        V1.0
 * 
****************************************************************************************/

#include "dr_handler.h"
#include "dr_public.h"
#include <string.h>
#include "msg_queue.h"


/**
 * @brief           处理从QT接收到的JSON字符串指令
 * @param cmd_json  QT发送过来的指令
 * @return          0   成功， -1  失败              
 */
int dr_cmd_handle(const char *cmd_json)
{
    if(cmd_json == NULL)
    {
        printf("[Warning] : dr_cmd_handle() cmd_json is empty!\n");
        return -1;
    }

    cJSON *root = cJSON_Parse(cmd_json);
    if(root == NULL)
    {
        const char *error_ptr = cJSON_GetErrorPtr();
        if(error_ptr != NULL)
        {
            printf("[Error]: JSON Analysis failed! Near the [%ld] character!\n", error_ptr-cmd_json);
            printf("         %s\n", error_ptr);
        }
        else
        {
            printf("[Error] : cJSON_Parse() analysis failed!\n");
        }
        return -1;
    }

    cJSON *key = cJSON_GetObjectItem(root, "key");
    if(key == NULL)
    {
        printf("[Error] : cJSON_GetObjectItem(root, \"key\") analysis failed!\n");
        return -1;
    }

    cJSON *data = cJSON_GetObjectItem(root, "data");
    if(data == NULL)
    {
        printf("cJSON_GetObjectItem(root, \"data\") analysis failed!\n");
        return -1;
    }
    
    if(key->valueint == 1)
    {
        struct Msg msg;
        msg.msg_type = MSG_QUEUE_TYPE;
        
        strcpy(msg.buf, cJSON_Print(data));

        // 发送到消息队列
        int id = msg_queue_init(MSG_QUEUE_NAME);
        if(msg_queue_send(id, (void*)&msg, sizeof(msg.buf), 0) == -1)
        {
            printf("send msg_queue error!\n");
        }
        printf("[msq] : write success\n");

    }
    else if(key->valueint == 2)
    {
        cJSON *data = cJSON_GetObjectItem(root, "data");
        if(data == NULL)
            return -1;
        if(data->valueint == 1)
        {
            dr_mode = 1;
        }
        else if(data->valueint == 2)
        {
            dr_mode = 2;
        }
        else if(data->valueint == 3)
        {
            dr_mode = 3;
        }
    }
    else if(key->valueint == 3)
    {
        if(dr_mode == 3)
        {
            dr_flush_flag = 1;
        }
    }

    return 0;
}